/*
 *  Copyright 2013 National Institute of Advanced Industrial Science and Technology
 *  
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.sss.server;

import java.rmi.RemoteException;

import org.slf4j.Logger;

import org.sss.common.CommonStatus;
import org.sss.common.JobDoneListener;
import org.sss.common.TaskStatus;
import org.sss.util.CallbackInterface;

public class JobDoneCallback<T> implements CallbackInterface<T> {
  private static Logger logger = SssServer.getLogger(JobDoneCallback.class);
  private TaskStatus taskStatus = null;

  public static <T> JobDoneCallback<T> wrap(JobDoneListener<T> l) {
    return new JobDoneCallback<T>(l);
  }
  public static <T> JobDoneCallback<T> wrap(JobDoneListener<T> listener, TaskStatus taskStatus) {
    return new JobDoneCallback<T>(listener, taskStatus);
  }

  JobDoneListener<T> listener;

  private JobDoneCallback(JobDoneListener<T> listener) {
    this.listener = listener;
    this.taskStatus = null;
  }
  private JobDoneCallback(JobDoneListener<T> listener, TaskStatus taskStatus) {
    this.listener = listener;
    this.taskStatus = taskStatus;
  }

  @Override
  public void callback(T arg) {
    if (taskStatus != null && arg instanceof CommonStatus) {
      CommonStatus status = (CommonStatus) arg;
      taskStatus.update(status);
    }
    try {
      listener.jobDone(arg);
    }
    catch (RemoteException e) {
      logger.error("Can't send job-done notify.", e);
    }
    // TODO: should handle other exception.
  }
}
